package com.lpf.handler;

import com.alibaba.fastjson.JSONObject;
import com.lpf.base.BaseApiService;
import com.lpf.entity.AppEntity;
import com.lpf.mapper.AppMapper;
import com.lpf.utils.BaseRedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 功能描述：验证AccessToken 是否正确
 */
@Component
public class AccessTokenInterceptor extends BaseApiService implements HandlerInterceptor {

    @Autowired
    private BaseRedisService baseRedisService;
    @Autowired
    private AppMapper appMapper;

    /**
     * 进入controller层之前拦截请求
     */
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        System.out.println("-----------------开始进入请求地址拦截------------------------");

        String accessToken = httpServletRequest.getParameter("accessToken");
        // 1、获取对应的accessToken
        if (StringUtils.isEmpty(accessToken)) {
            resultError("accessToken is null", httpServletResponse);
            return false;
        }

        // 2、使用accessToken查询redis对应的value（appId），如果没有获取到对应的appId，直接返回错误提示
        String appId = (String) baseRedisService.getString(accessToken);
        if (StringUtils.isEmpty(appId)) {
            resultError("this is accessToken invalid", httpServletResponse);
            return false;
        }

        // 3、如果使用accessToken查询redis，能够获取对应的value（appId），使用appId查询对应的app信息
        AppEntity app = appMapper.findAppId(appId);
        if (app == null) {
            resultError("not found app info", httpServletResponse);
            return false;
        }

        // 4、使用对应的appId查询数据库app信息，获取到is_flag状态，如果为1的情况下，直接不能调用下面。否则正常执行
        int isFlag = app.getIsFlag();
        if (isFlag == 1) {
            // 权限不足
            resultError("no permission", httpServletResponse);
            return false;
        }

        // 正常执行业务逻辑...
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {
        System.out.println("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        System.out.println("--------------视图渲染之后的操作------------------------------");
    }

    // 返回错误提示
    public void resultError(String errorMsg, HttpServletResponse httpServletResponse) throws IOException {
        PrintWriter printWriter = httpServletResponse.getWriter();
        printWriter.write(new JSONObject().toJSONString(setResultError(errorMsg)));
    }

}